//
//  ChinaCityChooseCell.m
//  WEIMO
//
//  Created by Lixiaoyong on 13-7-18.
//  Copyright (c) 2013年 广州从兴电子开发有限公司. All rights reserved.
//

#import "ChinaCityChooseCell.h"

#import "JSONKit.h"

@interface ChinaCityChooseCell ()
@property (nonatomic,retain) NSArray *provinceDatas; //省
@property (nonatomic,retain) NSArray *cityDatas;     //市
@property (nonatomic,retain) NSMutableArray *showCitys;     //显示的市区

@property (nonatomic,retain) NSDictionary *selectedProvince;
@end

@implementation ChinaCityChooseCell
@synthesize cityPickerView;
@synthesize provinceDatas,cityDatas,showCitys;
@synthesize selectedProvince;
@synthesize delegate;

- (void)dealloc
{
    self.cityPickerView = nil;
    self.provinceDatas = nil;
    self.cityDatas = nil;
    self.showCitys = nil;
    self.selectedProvince = nil;
    self.delegate = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.textLabel.textColor = [UIColor lightGrayColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [self getCityDatasFromLocalJson];
        
        self.cityPickerView = [[[UIPickerView alloc] initWithFrame:CGRectZero] autorelease];
        self.cityPickerView.dataSource = self;
        self.cityPickerView.delegate = self;
        self.cityPickerView.showsSelectionIndicator = YES;
        
        CGRect frame = self.inputView.frame;
		frame.size = [self.cityPickerView sizeThatFits:CGSizeZero];
		self.inputView.frame = frame;
        self.cityPickerView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    
    if (selected)
    {
        [self becomeFirstResponder];
    }
}

- (UIView *)inputView
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
		return nil;
	}
    else
    {
        return self.cityPickerView;
    }
}

- (UIView *)inputAccessoryView
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
		return nil;
	}
    else
    {
        UIToolbar *toolBar = [[[UIToolbar alloc] init] autorelease];
        toolBar.barStyle = UIBarStyleBlackTranslucent;
        toolBar.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [toolBar sizeToFit];
        CGRect frame = toolBar.frame;
        frame.size.height = 44.0f;
        toolBar.frame = frame;
        
        UIBarButtonItem *doneBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(clickedDoneButton)];
        UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        NSArray *toolArray = [NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn, nil];
        [toolBar setItems:toolArray];
        
        return toolBar;
    }
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)becomeFirstResponder
{
    return [super becomeFirstResponder];
}

- (BOOL)resignFirstResponder
{
	UITableView *tableView = (UITableView *)self.superview;
	[tableView deselectRowAtIndexPath:[tableView indexPathForCell:self] animated:YES];
    
	return [super resignFirstResponder];
}

#pragma mark - private methods

//获取数据
- (void)getCityDatasFromLocalJson
{
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSString *jsonString1 = [NSString stringWithContentsOfFile:filePath1 encoding:NSUTF8StringEncoding error:nil];
    self.provinceDatas = [jsonString1 objectFromJSONString];
    
    NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
    NSString *jsonString2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:nil];
    self.cityDatas = [jsonString2 objectFromJSONString];
    
    NSDictionary *dic = [self.provinceDatas objectAtIndex:0];
    [self getShowCitysFromCityDatas:[dic objectForKey:@"provinceid"]];
    self.detailTextLabel.text = [dic objectForKey:@"province"];
}

//获取所属地市数据
- (void)getShowCitysFromCityDatas:(NSString *)parentid
{
    self.showCitys = [[[NSMutableArray alloc] init] autorelease];
    NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] init];
    [firstDic setValue:@"全部" forKey:@"city"];
    [firstDic setValue:@"" forKey:@"cityid"];
    [self.showCitys addObject:firstDic];
    [firstDic release];
    
    for (int i=0; i<self.cityDatas.count; i++)
    {
        NSDictionary *otherDic = [self.cityDatas objectAtIndex:i];
        NSString *provinceId = [otherDic objectForKey:@"father"];
        if ([provinceId isEqualToString:parentid])
        {
            [self.showCitys addObject:otherDic];
        }
    }
}

- (void)clickedDoneButton
{
    [self resignFirstResponder];
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return self.provinceDatas.count;
    }
    else
    {
        return self.showCitys.count;
    }
}

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0)     //省
    {
        return ([[self.provinceDatas objectAtIndex:row] objectForKey:@"province"]);
    }
    else                    //市
    {
        return ([[self.showCitys objectAtIndex:row] objectForKey:@"city"]);
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *proId=@"";
    NSString *ciId= @"";
    if (component == 0)
    {
        self.selectedProvince = [self.provinceDatas objectAtIndex:row];
        
        self.detailTextLabel.text = [NSString stringWithFormat:@"%@",[self.selectedProvince objectForKey:@"province"]];
        
        [self getShowCitysFromCityDatas:[[self.provinceDatas objectAtIndex:row] objectForKey:@"provinceid"]];
        
        [self.cityPickerView selectRow:0 inComponent:1 animated:YES];
        [self.cityPickerView reloadComponent:1];
    }
    else
    {
        NSDictionary *selectedDic = [self.showCitys objectAtIndex:row];
        self.detailTextLabel.text = [NSString stringWithFormat:@"%@-%@",[self.selectedProvince objectForKey:@"province"],[selectedDic objectForKey:@"city"]];
        ciId  = [selectedDic objectForKey:@"cityid"];

    }
    
     proId = [self.selectedProvince objectForKey:@"provinceid"];
    [self.delegate returnChoosedChinaCityWithProvinceId:proId andCityId:ciId];
}

@end